﻿using FluorineFx.Json;
using HashidsNet;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;

namespace lxwmvc
{
    public class zfcontroller
    {
        public static void help(pagebase pb)
        {
            pb.cancelview();

            dataloger.info("<IP>:"+requesthelper.clientip());
            pb.write("稍后访问!");
        }

        static string mstr = @"";


        public static void m(pagebase pb)
        {
            string regex = "/(\\d+)\\.m4a\\?fromtag=\\d+(\\s)*\'\\)\">&bull;\\s([^<]+)";
            System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline)
                        | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);

            var t = reg.Matches(mstr);
            string ret = "aaa";
            foreach (Match m in t)
            {
                ret += "," + m.Groups[1].Value + "," + m.Groups[3].Value;
            }

            pb.write(ret);
        }


        public static void model(pagebase pb)
        {
            pb.cancelview();
            applicationhelper.CreateModels("");
        }

        public static void get(pagebase pb)
        {
            var tt = GetArticleID("asdasdaaa", "http://toutiao.com/a6212746313372385538/", "asdasddd","admin");

            pb.redirect("/s?u=" + tt);
        }

        public static Bitmap GetImageFromBase64(string base64string)
        {
            byte[] b = Convert.FromBase64String(base64string);
            MemoryStream ms = new MemoryStream(b);
            Bitmap bitmap = new Bitmap(ms);
            return bitmap;
        }

        class ThreadDoUrl
        {
            public string url = "";
            public string _FormUserName = "";
            public string FormUserName = "";
            /// <summary>
            /// 状态
            /// </summary>
            public int ZT = 0;
            public string title = "";
            public string des = "";
            public string img = "";

            public string _ToUserName = "";
            public string USER_INFO = "";
            public string USER_NICKNAME = "";
        }
        /// <summary>
        /// 接收服务器端
        /// </summary>
        /// <param name="pb"></param>
        public static void msg(pagebase pb)
        {
            try
            {
                var body = "";
                using (StreamReader sb = new StreamReader(pb.Request.InputStream, Encoding.UTF8))
                {
                    body = sb.ReadToEnd();
                }
                //得到上传过来的信息
                ThreadDoUrl obj = JavaScriptConvert.DeserializeObject<ThreadDoUrl>(body) as ThreadDoUrl;
                doMessage(pb,obj);
            }
            catch (Exception err)
            {
                dataloger.fatal("msg(pagebase pb)", err);
                pb.write("");
            }
        }
        static Dictionary<string, bool> USER_ROBOT = new Dictionary<string, bool>();
        /// <summary>
        /// 处理消息
        /// </summary>
        /// <param name="pb"></param>
        /// <param name="obj"></param>
        private static int doMessage(pagebase pb, ThreadDoUrl obj)
        {
            string msg = obj.url;
            string _FormUserName = obj._FormUserName;

            //处理群消息
            
            if (_FormUserName.StartsWith("@@") || obj._ToUserName.StartsWith("@@"))
            {
                var index = msg.IndexOf(":");
                if(index > 0) msg = msg.Substring(index + 1);
            }

            {//机器人部分
                if (msg == "闭嘴" || msg == "张嘴" || USER_ROBOT.ContainsKey(_FormUserName))
                {

                    //在群里面说的话
                    if (obj._ToUserName.StartsWith("@@"))
                    {
                        //不管群里面谁说话
                        _FormUserName = obj._ToUserName;
                    }

                    if (msg == "闭嘴")
                    {
                        USER_ROBOT[_FormUserName] = false;
                        USER_ROBOT.Remove(_FormUserName);
                        return returnDoMessage("机器人闭嘴",pb, obj, "关闭.");
                    }

                    if (msg == "张嘴")
                    {
                        USER_ROBOT[_FormUserName] = true;
                        return returnDoMessage("机器人张嘴",pb, obj, "启动.");
                    }

                    //机器人对话
                    return returnDoMessage("机器人回答",pb, obj, fmtmsg(GetMSG(msg, _FormUserName)));
                }
            }

            {
                //处理消息反馈，不做任何处理
                if (msg.StartsWith("<msg><op id='1'>"))
                    return returnDoMessage("<msg><op id='1'>", pb, obj, "");
            }

            {
                //处理图片，不考虑
                if (msg.StartsWith("<msg><img length="))
                {
                    //if (USER_AD.ContainsKey(_FormUserName))
                    //{
                    //    var MsgID = obj["MsgId"] + "";
                    //    SendMsg(_FormUserName, _ToUserName, "正在处理广告，请稍后...", false);
                    //    UploadWxImage(MsgID, _FormUserName, FormUserName, USER_AD[_FormUserName]);
                    //    Console.WriteLine("3=>" + MsgID);
                    //}
                    return returnDoMessage("<msg><img length=", pb, obj, "");
                }
            }

            {
                //处理消息
                if (msg.StartsWith("<msg>") && msg.Contains("<url>"))
                {
                    var url = WeiXin_Fun.SubString(msg, "<url>", "</url>");
                    if (url.StartsWith("<![CDATA", StringComparison.OrdinalIgnoreCase))
                        return returnDoMessage("<![CDATA", pb, obj, "");

                    //处理url
                    var r = c1(obj, url);



                    var t = returnDoMessage("url转换",pb, obj, r);
                    return t;
                }
            }

            {
                //处理其他信息
                if (msg.StartsWith("<msg>"))
                {
                    return returnDoMessage("<msg>",pb, obj, "");
                }

                if (_FormUserName == obj.USER_INFO)
                {
                    //Console.WriteLine("5=>" + _FormUserName + ">" + _ToUserName);
                    return returnDoMessage("我自己",pb, obj, "");
                }

                if (_FormUserName.StartsWith("@@")|| obj._ToUserName.StartsWith("@@"))
                {
                    var index = msg.IndexOf(":");
                    if (index > 0) msg = msg.Substring(index + 1);
                    return returnDoMessage("群消息@@", pb, obj, "");
                }

                if (obj.FormUserName.Contains("微信团队"))
                {
                    //Console.WriteLine("5=>" + _FormUserName + ">" + _ToUserName);
                    return returnDoMessage("微信团队", pb, obj, "");
                }

                if (msg == "0")
                {
                    var neirong = @"------ 开始提示 ------
* <<广告+>>给您带来分享新体验；
* 如需帮助、更改广告、操作说明，请回复“0” 

------ 功能提示 ------
广告家介绍
ad.zituibao.com/hello
更换广告
ad.zituibao.com/set
广告统计
ad.zituibao.com/r
视频讲解
ad.zituibao.com/tv


";
                    return returnDoMessage("帮助",pb, obj, neirong.Replace("\r", "\n").Replace("\n\n", "\n"));
                }
            }

            return  returnDoMessage("其他", pb, obj, "");
        }


        static string c1(ThreadDoUrl obj,string url)
        {
            try
            {
                string uid = obj._FormUserName;
                string name = obj.FormUserName;

                string title = obj.title;
                string des = obj.des;
                string img = obj.img;

                CreateUser(uid, name);

                var newurl = "";
                if (url.StartsWith("http://ad.zituibao.com", StringComparison.OrdinalIgnoreCase))
                {
                    return "文章已经被转换过，不允许再转换。";
                }

                if (url.Contains("zituibao.com"))
                {
                    return "文章已经被转换过，不允许再转换。";
                }

                if (!url.StartsWith("http://mp.weixin.qq.com", StringComparison.OrdinalIgnoreCase))
                {
                    if (img == "")
                    {
                        throw new Exception("转换失败:" + url);
                    }
                    else
                    {

                        Image image = imagehelper.GetImageFromBase64(img);
                        var filename = DateTime.Now.ToString("HHmmssfff") + WeiXin_Fun.CreateNonceStr(16) + ".jpg";
                        //保存文件
                        image.Save(Path.Combine(HttpContext.Current.Server.MapPath("/AdImages"), filename));
                        if (image != null) image.Dispose();

                        filename = "/AdImages/" + filename;
                        newurl = SaveArticle("WAIBU", uid, title, des, filename, url, name, obj.USER_NICKNAME);
                    }
                }
                else
                {
                    newurl = GetArticleID(uid, url, name, obj.USER_NICKNAME);
                }

                var code = newurl;

                var where = "";

                var art = queryhelper.get<_Articles>("select *  from Articles where code=@0", code);
                if (art.ArticleID != "WAIBU")
                    where = "\n@您可以编辑文章\nhttp://" + weixincontroller.domain + "/s00?u=" + newurl;
                //抓取完毕，输出新的地址
                return ("@转换完成，请预览并分享\nhttp://" + weixincontroller.domain + "/s?u=" + newurl + where+ "\n\n其他操作，请回复“0”");

            }
            catch (Exception err)
            {
                dataloger.fatal("c(pagebase pb)", err);
                return ("");
            }
        }
        /// <summary>
        /// 生成数据库记录
        /// </summary>
        /// <param name="pb"></param>
        /// <param name="obj"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        private static int returnDoMessage(string flag,pagebase pb, ThreadDoUrl obj, string p)
        {
            var model = new supermodel("neirong");
            model["neirong"] = obj.url;
            model["_FormUserName"] = obj._FormUserName;
            model["FormUserName"] = obj.FormUserName;
            model["title"] = obj.title;
            model["des"] = obj.des;
            model["_ToUserName"] = obj._ToUserName;
            model["USER_INFO"] = obj.USER_INFO;
            model["msg"] = p;
            model["tianjiariqi"] = DateTime.Now;
            model["flag"] = flag;

            var t = model.saveorupdate().identity;
            pb.write(p);

            return t;
        }

        /// <summary>
        /// 这里需要特殊对话
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        private static string fmtmsg(string p)
        {
            return p.Replace("图灵","“广告加”");
        }

        static string GetMSG(string msg, string yonghu)
        {
            try
            {
                var content = "";
                using (WebClient wb = new WebClient())
                {
                    wb.Encoding = Encoding.UTF8;
                    content = wb.DownloadString("http://www.tuling123.com/openapi/api?userid=" + yonghu + "&key=335d358c3d4e94fd0f8fd3e13dcd81e1&info=" +
                        msg
                        );
                }

                JavaScriptObject obj = JavaScriptConvert.DeserializeObject(content) as JavaScriptObject;

                return obj["text"] + "";
            }
            catch
            {
                return "回答不了!";
            }
        }

        /*
         * 判断为空的ID或者是判断用户是否缴费，以此使用默认ID广告
         * TODO
         */
        //public static void c(pagebase pb)
        //{
        //    try
        //    {
        //        var body = "";
        //        using (StreamReader sb = new StreamReader(pb.Request.InputStream, Encoding.UTF8))
        //        {
        //            body = sb.ReadToEnd();
        //        }
        //        //dataloger.info("titletitletitletitle>>" + body);

        //        var obj = JavaScriptConvert.DeserializeObject(body) as JavaScriptObject;

        //        //string url, string uid
        //        string url = obj["purl"]+"";
        //        string uid =  obj["uid"] + "";
        //        string name =  obj["name"] + "";

        //        string title =obj["title"] + "";
        //        string des = obj["des"] + "";
        //        string img = obj["img"] + "";

               

        //        //#if DEBUG
        //        //                url = "http://mp.weixin.qq.com/s?__biz=MjM5NjAyMzcyMA==&mid=223693039&idx=2&sn=f45db1501aeb3e1906b76edafd9042fb&scene=23&srcid=1008b5TkntvajAj9oi1YIA2j#rd&ADUIN=7103505&ADSESSION=1444267023&ADTAG=CLIENT.QQ.5425_.0&ADPUBNO=26509";
        //        //                uid = "admin";
        //        //#endif

        //        CreateUser(uid, name);

        //        var newurl = "";
        //        if (url.StartsWith("http://ad.zituibao.com", StringComparison.OrdinalIgnoreCase))
        //        {
        //            pb.write("文章已经被转换过，不允许再转换。");
        //            return;//
        //        }

        //        if (url.Contains("zituibao.com"))
        //        {
        //            pb.write("文章已经被转换过，不允许再转换。");
        //            return;//
        //        }

        //        if (!url.StartsWith("http://mp.weixin.qq.com", StringComparison.OrdinalIgnoreCase))
        //        {
        //            if (img == "")
        //            {
        //                throw new Exception("转换失败:" + url);
        //            }
        //            else
        //            {

        //                Image image = imagehelper.GetImageFromBase64(img);

        //                var filename = DateTime.Now.ToString("HHmmssfff") + WeiXin_Fun.CreateNonceStr(16) + ".jpg";
        //                //保存文件
        //                image.Save(Path.Combine(pb.Server.MapPath("/AdImages"), filename));
        //                if (image != null) image.Dispose();

        //                filename = "/AdImages/" + filename;
        //                newurl = SaveArticle("WAIBU", uid, title, des, filename, url, name, );
        //            }
        //        }
        //        else
        //        {
        //            newurl = GetArticleID(uid, url, name);
        //        }
        //        //抓取完毕，输出新的地址
        //        pb.write("转换完成，请预览并分享\nhttp://" + weixincontroller.domain + "/s?u=" + newurl+"\n\n如需修改广告，请回复“0”");

        //    }
        //    catch (Exception err)
        //    {
        //        dataloger.fatal("c(pagebase pb)", err);
        //        pb.write("转换失败!");
        //    }
        //}

        public static void click(pagebase pb)
        {
            var code = pb.v_ss("code");
            //增加点击次数
            queryhelper.execute("update Articles set ClickCount=ClickCount+1 where code=@0", code);
            pb.write("ok");
        }

        ///// <summary>
        ///// 接收图片
        ///// </summary>
        ///// <param name="pb"></param>
        //static void u(pagebase pb)
        //{
        //    try
        //    {
        //        //string url, string uid
        //        string uid = pb.v_s("uid");
        //        string name = pb.v_s("name");
        //        string AD = pb.v_s("ad");
        //        var adid = AD.toint32(1);

        //        string body = "";
        //        using (StreamReader sb = new StreamReader(pb.Request.InputStream, Encoding.UTF8))
        //        {
        //            body = sb.ReadToEnd();
        //        }

        //        //判断用户是否可以正常用
        //        var user = CreateUser(uid, name);
        //        //代表是非注册用户
        //        if (user.UserType == 0 && adid == 3)
        //        {
        //            pb.write("免费用户只能修改前两条广告");
        //            return;
        //        }



        //        Image image = imagehelper.GetImageFromBase64(body);
        //        Bitmap map = new Bitmap(image, 640, 119);
        //        var filename = DateTime.Now.ToString("HHmmssfff") + WeiXin_Fun.CreateNonceStr(16) + ".jpg";
        //        //保存文件
        //        map.Save(Path.Combine(pb.Server.MapPath("/AdImages"), filename));
        //        if (image != null) image.Dispose();
        //        if (map != null) map.Dispose();

        //        //输入广告1 提示发送广告图片过来，建议大小为640x100  广告接收完毕，可以继续发送广告链接 例如 http://a.com

        //        //输入广告2

        //        //输入广告3


        //        var ad = queryhelper.get<_ZTBAD>("select * from ZTBAD where ZTBUserID=@0 and  xuhao=@1", uid, adid);
        //        if (ad == null) ad = new _ZTBAD();
        //        ad.ZTBUserID = uid;
        //        ad.ZTBUserName = name;
        //        ad.url = "/AdImages/" + filename;
        //        ad.xuhao = adid;
        //        ad.saveorupdate();

        //        pb.write("广告接收完毕，可以继续发送广告链接 例如 http://a.com");


        //    }
        //    catch (Exception err)
        //    {
        //        dataloger.error("u(pagebase pb)", err);
        //        pb.write("广告接收失败!");
        //    }
        //}

        static _ZTBUsers CreateUser(string uid, string name)
        {
            var user = queryhelper.get<_ZTBUsers>("select * from ZTBUsers where ZTBUserID=@0", uid);
            if (user == null)
            {
                user = new _ZTBUsers();
                user.ZTBUserID = uid;
                user.UserType = 0;
                user.UserName = name;

            }
            user.LastLogonTime = DateTime.Now;

            user.saveorupdate();
            return user;
        }

//        static void a(pagebase pb)
//        {
//            try
//            {
//                //string url, string uid
//                string uid = pb.v_s("uid");
//                string name = pb.v_s("name");
//                string AD = pb.v_s("ad");
//                string url = pb.v_s("purl");

//                var adid = AD.toint32(1);
//                var user = CreateUser(uid, name);
//                //代表是非注册用户
//                if (user.UserType == 0 && adid == 3)
//                {
//                    pb.write("免费用户只能修改前两条广告");
//                    return;
//                }

//                var ad = queryhelper.get<_ZTBAD>("select * from ZTBAD where ZTBUserID=@0 and  xuhao=@1", uid, adid);
//                if (ad == null) ad = new _ZTBAD();
//                ad.ZTBUserID = uid;
//                ad.ZTBUserName = name;
//                ad.xuhao = adid;
//                ad.link = url;
//                ad.saveorupdate();

//                pb.write(@"广告链接已经修改
//广告{0}
//广告图片
//{1}
//广告链接
//{2}
//", AD, "http://" + weixincontroller.domain + ad.url, ad.link);


//            }
//            catch (Exception err)
//            {
//                dataloger.error("a(pagebase pb)", err);
//                pb.write("广告接收失败!");
//            }
//        }

        /*
         * 1、取得URL；
         * 2、获取整个URL的HTMLData；
         * 3、处理HTMLData，怎么处理：a，获取html中的所有图片；b，获取html中的动画；c，附加到文档中的广告；增加广告点击计数器
         * 4、获取最新的文章的ID；
         * 5、保存文章的地址；
         * 6、返回文章的地址
         * 
         * 
         */
        private static string GetArticleID(String uid, string url,string name,string openid)
        {
            using (WebClient wc = new WebClient())
            {
                //下载页面源文件并将其转换成UTF8编码格式的STRING
                string htmlData = Encoding.UTF8.GetString(wc.DownloadData(string.Format(url)));

                //HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                //req.Method = "GET";
                //HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                //string htmlCharset = "GBK";
                //Encoding htmlEncoding = Encoding.GetEncoding(htmlCharset);
                //StreamReader sr = new StreamReader(resp.GetResponseStream());
                //string htmlData = sr.ReadToEnd();

                //生成文章ID，新建文章所在的文件夹，返回文章的全路径，取得ID


                string aid = GetSerialNumber();
                String folderpath = HandleArticleSerialNumber(uid);
                //String aid = folderpath.Substring(folderpath.LastIndexOf("10012"), 18);


                //处理下载下来的文本的内容
                return HandleHtmlContent(aid, uid, folderpath, htmlData, name,openid);
            }
        }

        internal static string GetSerialNumber()
        {
            return DateTime.Now.ToString("HHmmssfff") + WeiXin_Fun.CreateNonceStr(16);
        }

        static Hashids hs = new Hashids("this is my lxwsalt");
        private static string HandleArticleSerialNumber(string aid)
        {
            //返回根目录的全路径：\Articles\20150910\aid\ aid=100120021509000001

            //在article下面创建文件夹"\Articles\20150910\aid\", 全路径\Articles\20150910\aid\aid.html
            return CreateFolder(aid);
        }

        internal static String CreateFolder(string uid)
        {
            String articleFolderPath = System.Web.HttpContext.Current.Server.MapPath(Path.Combine(("/Articles/" + DateTime.Now.ToString("yyyyMMdd/HHmmss")), uid));
            if (!Directory.Exists(articleFolderPath))//创建日期目录
                Directory.CreateDirectory(articleFolderPath);


            return articleFolderPath;
        }

        private static string HandleHtmlContent(string aid, string uid, string folderpath, string htmlData,string name,string openid)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(htmlData);


            //文章的title处理；
            String title = extractTitle(doc, htmlData);

            //文章的摘要处理；
            String summary = extractSummary(htmlData);
            //文章的缩略图处理；
            String imageURL = extractImageURL(htmlData, folderpath);
            //文章原始部分的图片处理；
            doc = imageHandle(doc, aid, folderpath);
            //文章部分的音视频处理；
            doc = vedioHandle(doc, aid, folderpath);

            //去掉所有的脚本
            foreach (HtmlNode script in doc.DocumentNode.Descendants("script").ToArray())
                script.Remove();

            //文章部分的广告处理，增加广告点击计数器

            //先讲doc输出为html，最后将文章保存到磁盘本地
            htmlData = doc.DocumentNode.WriteTo();

            String uri = CreateArticle(aid, htmlData, folderpath);
            //在数据库中保存文章的记录,初始默认文章都为正常状态，要有一个后台审核功能
            return SaveArticle(aid, uid, title, summary, imageURL, uri, name, openid);

        }

        internal static string SaveArticle(string aid, string uid, string title, string summary, string imageURL, string url, string name, string USER_NICKNAME)
        {
            _Articles art = new _Articles();
            art.ArticleID = aid;
            art.ZTBUserID = uid;
            art.IsAudit = 0;
            art.Status = 0;
            art.Title = title;
            art.Summary = summary;
            art.ImageUrl = imageURL;
            art.URL = url;
            art.ReadCount = 0;
            art.ClickCount = 0;
            art.ZTBUserName = name;
            art.ReleaseTime = DateTime.Now;
            

            var ret = art.saveorupdate();
            art.clear();
            art.Code = hs.Encode(art.ID.Value+100000);
            //首先记录是管理员的文章，如果有人第一次预览，就记录是谁的文章
            art.openid = USER_NICKNAME;
            art.saveorupdate();

            return art.Code;
        }

        internal static String CreateArticle(string aid, string htmlData, string articleFolderPath)
        {
            String articleName = aid + ".html";
            string path = Path.Combine(articleFolderPath, articleName);

            try
            {
                using (StreamWriter sw = new StreamWriter(path)) 
                {
                    sw.WriteLine(htmlData);
                    sw.Flush();
                    sw.Close();
                }
            }
            catch (Exception em)
            {
                Console.WriteLine(em.Message.ToString());
            }

            return path;
        }
        /*----------------------------------------------HTML分析子程序----------------------------------------------------------------*/
        private static string extractTitle(HtmlAgilityPack.HtmlDocument doc, string htmlData)
        {
            string title = doc.DocumentNode.SelectSingleNode("//title").InnerText;

            if (title == null)
            {
                Regex reg = new Regex(@"var msg_title[\s\S]*?var");

                MatchCollection mc = reg.Matches(htmlData);
                if (mc.Count > 0)
                {
                    foreach (Match subm in mc)
                    {
                        title = subm.Groups[0].Value;
                        title = title.Substring((title.IndexOf("\"") + 1), (title.LastIndexOf(";") - title.IndexOf("\"") - 2));
                    }
                }
            }
            if (title == null)
                title = "自推宝，我的广告我做主！";

            return title;

        }

        private static string extractSummary(string htmlData)
        {
            string summary = null;
            //var msg_title
            Regex reg = new Regex(@"var msg_desc[\s\S]*?var");

            MatchCollection mc = reg.Matches(htmlData);
            if (mc.Count > 0)
            {
                foreach (Match subm in mc)
                {
                    summary = subm.Groups[0].Value;
                    summary = summary.Substring((summary.IndexOf("\"") + 1), (summary.LastIndexOf(";") - summary.IndexOf("\"") - 2));
                }
            }
            else
            {
                summary = "自推宝||自媒体||自营销||微信广告||微信推广||微信传播||我的广告听我的||我的推广我做主";
            }
            return summary;
        }

        private static string extractImageURL(string htmlData, string folderpath)
        {
            string cdnimage = null;
            //var msg_title
            Regex reg = new Regex(@"var msg_cdn_url[\s\S]*?var");

            MatchCollection mc = reg.Matches(htmlData);
            if (mc.Count > 0)
            {
                Match submatch = mc[0];
                cdnimage = submatch.Groups[0].Value;
                cdnimage = cdnimage.Substring((cdnimage.IndexOf("\"") + 1), (cdnimage.LastIndexOf(";") - cdnimage.IndexOf("\"") - 2));
                try
                {
                    using (WebClient wc = new WebClient())
                    {

                        string suffix = cdnimage.Substring((cdnimage.LastIndexOf("=") + 1), 3);
                        if (suffix.Equals("jpe")) suffix = suffix + "g";

                        string filename = "cover." + suffix;
                        wc.DownloadFile(cdnimage, Path.Combine(folderpath, filename));

                        cdnimage = Path.Combine(HttpContext.Current.Request.ApplicationPath, folderpath.Substring(folderpath.IndexOf("Article")), filename);
                    }
                }
                catch (Exception e)
                {
                    dataloger.fatal("extractImageURL", e);
                    cdnimage = Path.Combine(HttpContext.Current.Request.ApplicationPath, "Adimages/zituibao.jpg");
                }
            }
            else
            {
                cdnimage = Path.Combine(HttpContext.Current.Request.ApplicationPath, "Adimages/zituibao.jpg");
            }
            return cdnimage;
        }

        private static HtmlDocument imageHandle(HtmlDocument doc, string aid, string folderpath)
        {
            //Regex reg = new Regex(@"(?i)<img[^>]*?\ssrc\s*=\s*(['""]?)(?<src>[^'""\s>]+)\1[^>]*>");
            //MatchCollection mc = reg.Matches(htmlData);


            /*
             * 处理脚本中的img
             * 1、处理封面cover的img <div class="rich_media_thumb_wrp">
             * 2、找到可能有脚本的标签（需要不断更新迭代），一个脚本一个脚本的排查更新 ----太辛苦麻烦，感觉不值得
             * 3、判断标签中是否有脚本
             * 4、将脚本语言直接替换成img标签
             * // 作为开头使用 / 分隔符@ 属性标志[] 属性选择器
             */
            //封面的图片
            string imgTag = null;
            HtmlNodeCollection scriptCollection = doc.DocumentNode.SelectNodes("//div[@class='rich_media_thumb_wrp']/script");
            if (scriptCollection != null)
            {
                for (int i = 0; i < scriptCollection.Count; i++)
                {
                    HtmlNode node = scriptCollection[i];
                    HtmlNode imgNode = null;
                    string script = node.InnerHtml;
                    if (script.Contains("<img") && (script.Contains("data-src=") || script.Contains("src=")))
                    {
                        if (script.IndexOf("http://mmbiz.qpic.cn/") > 0)
                        {
                            string imgurl = script.Substring(script.IndexOf("http://mmbiz.qpic.cn/"));
                            imgurl = imgurl.Substring(0, imgurl.IndexOf("\""));
                            imgTag = "<img class=\"rich_media_thumb\" width=\"auto\" data-src=\"" + imgurl + "\" />";

                            imgNode = HtmlNode.CreateNode(imgTag); ;

                        }
                    }
                    if (imgNode != null) node.ParentNode.AppendChild(imgNode);
                }
            }

            /*
             * 图片处理：
             * 1、获取html文档中存在图片的节点
             * 2、获取图片的链接，将图片下载到本地，重新命名另存
             * 3、更新文档中节点的值，src或这data-src
             * 4、遍历所有图片* 
             * 
             */
            string srcValue = null;
            string datasrcValue = null;
            string imgPath = null;

            HtmlNodeCollection imgCollection = doc.DocumentNode.SelectNodes("//img");

            if (imgCollection != null)
            {
                for (int i = 0; i < imgCollection.Count; i++)
                {
                    HtmlNode node = imgCollection[i];
                    if (node.Attributes["src"] != null && !String.IsNullOrEmpty(node.Attributes["src"].Value))
                    {
                        srcValue = node.Attributes["src"].Value;
                        imgPath = HandleImagePath(srcValue, 0, folderpath, null);
                        node.Attributes["src"].Value = imgPath;
                    }
                    if (node.Attributes["data-src"] != null && !String.IsNullOrEmpty(node.Attributes["data-src"].Value))
                    {
                        string datatype = null;

                        //分析img字符串
                        if ((node.Attributes["url"] != null) && !String.IsNullOrEmpty(node.Attributes["url"].Value))
                        {
                            datasrcValue = node.Attributes["url"].Value;
                            if (datasrcValue.Contains("&")) datasrcValue = datasrcValue.Substring(0, (datasrcValue.IndexOf("&") - 1));
                        }
                        else
                        {
                            datasrcValue = node.Attributes["data-src"].Value;
                            if (datasrcValue.Contains("&")) datasrcValue = datasrcValue.Substring(0, (datasrcValue.IndexOf("&") - 1));
                        }
                        if (node.Attributes["data-type"] != null && !String.IsNullOrEmpty(node.Attributes["data-type"].Value))
                            datatype = node.Attributes["data-type"].Value;
                        imgPath = HandleImagePath(datasrcValue, 1, folderpath, datatype);
                        node.SetAttributeValue("src", imgPath);

                        //删除多余项
                        if (node.Attributes["data-src"] != null) node.Attributes.Remove("data-src");
                        if (node.Attributes["source"] != null) node.Attributes.Remove("source");
                        if (node.Attributes["url"] != null) node.Attributes.Remove("url");
                        if (node.Attributes["data-cke-saved-src"] != null) node.Attributes.Remove("data-cke-saved-src");

                    }
                }
            }

            return doc;

        }

        //type=0 src字段来源 Name: "src", Value: "http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/common/icon_loading_white2805ea.gif"
        //type=1 data-src字段来源 Name: "data-src", Value: "http://mmbiz.qpic.cn/mmbiz/EfY115GicZB57RWw1oIW1KyJQ3pWC8qV1EFs1sDSeOdbfmfC6RLDDAPFDZwNPiaxVibibISfx7aKeUK5DomBHibpzYA/0?wx_fmt=jpeg&..."
        private static string shareimage1 = "http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/appmsg/emotion/icon_emotion_switch.2x278965.png";
        private static string shareimage2 = "http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/appmsg/emotion/icon_emotion_switch_active.2x278965.png";
        private static string shareimage3 = "http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/common/icon_loading_white2805ea.gif";
        private static string shareimage4 = "";
        private static Random rd = new Random();
        private static string HandleImagePath(string srcValue, int type, string folderpath, string datatype)
        {

            string path = folderpath.Substring(folderpath.IndexOf("Article"));

            //src, 非html5-----------------------------------------------
            if (type == 0)
            {
                if (srcValue == shareimage1) return "/images/public/icon_emotion_switch.2x278965.png";
                if (srcValue == shareimage2) return "/images/public/icon_emotion_switch_active.2x278965.png";
                if (srcValue == shareimage3) return "/images/public/icon_loading_white2805ea.gif";
                if (srcValue.StartsWith(shareimage4)) return "/images/public/index.png";
                try
                {
                    using (WebClient wc = new WebClient())
                    {
                        string filename = "";
                        if (srcValue.LastIndexOf("=") > 0)
                        {
                            try
                            {
                                string suffix = srcValue.Substring((srcValue.LastIndexOf("=") + 1), 3);
                                if (suffix.Equals("jpe")) suffix = suffix + "g";
                                filename = "img" + rd.Next(100000, 1000000).ToString() + "." + suffix;
                            }
                            catch {
                                filename = "img" + rd.Next(100000, 1000000).ToString() + ".jpg";
                            }
                            wc.DownloadFile(srcValue, Path.Combine(folderpath, filename));
                        }
                        else
                        {
                            filename = "img" + rd.Next(100000, 1000000).ToString() + ".jpg";
                            wc.DownloadFile(srcValue, Path.Combine(folderpath, filename));
                        }
                        

                        return Path.Combine(HttpContext.Current.Request.ApplicationPath, path, filename);
                    }
                }
                catch (Exception e)
                {
                    return "";
                }

            }
            //data-src
            if (type == 1)
            {
                try
                {
                    using (WebClient wc = new WebClient())
                    {

                        string filename = null;

                        //todo 20151013 李晓伟修改
                        if (String.IsNullOrEmpty(datatype))
                        {
                            if (srcValue.LastIndexOf("=") > 0)
                            {
                                if (srcValue.Split('?')[0].EndsWith("/0"))
                                {
                                    filename = "img" + rd.Next(100000, 1000000).ToString() + ".jpg";
                                }
                                else
                                {
                                    try
                                    {
                                        string suffix = srcValue.Substring((srcValue.LastIndexOf("=") + 1), 3);
                                        if (suffix.Equals("jpe")) suffix = suffix + "g";
                                        filename = "img" + rd.Next(100000, 1000000).ToString() + "." + suffix;
                                    }
                                    catch { }
                                    filename = "img" + rd.Next(100000, 1000000).ToString() + ".jpg";
                                }
                            }
                            else
                            {
                                filename = "img" + rd.Next(100000, 1000000).ToString() + ".jpg";
                            }
                        }
                        else
                            filename = "img" + rd.Next(100000, 1000000).ToString() + "." + datatype;

                        wc.DownloadFile(srcValue, Path.Combine(folderpath, filename));

                        return Path.Combine(HttpContext.Current.Request.ApplicationPath, path, filename);
                    }
                }
                catch (Exception e)
                {

                    return "";
                }
            }

            return "";

        }


        private static HtmlDocument vedioHandle(HtmlDocument doc, string aid, string folderpath)
        {
            HtmlNodeCollection videoCollection = doc.DocumentNode.SelectNodes("//iframe[@class='video_iframe']");
            if (videoCollection != null)
            {
                for (int i = 0; i < videoCollection.Count; i++)
                {
                    HtmlNode node = videoCollection[i];
                    string videoURL = null;
                    //Start - 处理QQ视频方法
                    if ((node.Attributes["data-src"] != null) && !String.IsNullOrEmpty(node.Attributes["data-src"].Value))
                    {
                        videoURL = node.Attributes["data-src"].Value;
                        videoURL = videoURL.Replace("auto=0", "auto=0");
                    }
                    if (node.Attributes["scrolling"] == null) 
                        node.Attributes.Add("scrolling", "no");


                    if (node.Attributes["src"] == null)
                        node.Attributes.Add("src", videoURL.Replace("preview.html", "player.html"));
                    else
                    {
                        if (videoURL == null) videoURL = node.Attributes["src"].Value;
                        node.Attributes["src"].Value = videoURL.Replace("preview.html", "player.html");
                    }

                    //node.Attributes["style"].Value = " z-index:999; width: 500px ! important; height: 375px ! important; overflow: hidden;";
                    //node.Attributes["width"].Value = "500px";
                    //node.Attributes["height"].Value = "375px";
                    //End - 处理QQ视频方法

                    try
                    {
                       
                        node.Attributes["style"].Value = "";
                        node.Attributes["data-src"].Value = "";
                    }
                    catch { }
                }

            }
            return doc;
        }
    }
}
